package logic

import (
	"context"
	"encoding/json"
	"furniture/models/cache"
	"furniture/models/mysql"
	"time"

	"furniture/furniturerpc/furniturerpc"
	"furniture/furniturerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FurnitureListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFurnitureListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FurnitureListLogic {
	return &FurnitureListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FurnitureListLogic) FurnitureList(in *furniturerpc.FurnitureListRequest) (*furniturerpc.FurnitureListResponse, error) {
	// todo: add your logic here and delete this line
	var furnitures []mysql.FurnitureClass

	get := cache.Rdb.Get(l.ctx, "furnitureList")

	if get.Val() == "" {
		mysql.DB.Table("furnitures").
			Select("furnitures.*, classes.name as class_name, brands.name as brand_name").
			Joins("left join classes on classes.id = furnitures.class_id").
			Joins("left join brands on brands.id = furnitures.brand_id").
			Find(&furnitures)
		marshal, _ := json.Marshal(furnitures)
		cache.Rdb.Set(l.ctx, "furnitureList", marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(get.Val()), &furnitures)
	}
	var furnitureList []*furniturerpc.FurnitureList
	for _, furniture := range furnitures {
		list := furniturerpc.FurnitureList{
			Title:     furniture.Title,
			ClassName: furniture.ClassName,
			BrandName: furniture.BrandName,
		}
		furnitureList = append(furnitureList, &list)
	}
	return &furniturerpc.FurnitureListResponse{
		List: furnitureList,
	}, nil
}
